package com.alibaba.travel.thirdpart.scheduled;

import com.alibaba.travel.thirdpart.entity.UserLikesRecordEntity;
import com.alibaba.travel.thirdpart.service.UserLikesRecordService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: where
 * @Date: 2023/03/06/10:42
 * @Description: 定期更新点赞数
 */
@Service
public class LikesRefreshScheduled {
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 每20分钟，进行Redis点赞状态刷新
     */
    @Scheduled(cron = "0 0/20 * * * ?")
    public void refreshStatus() {
        // 获取所有关键词
        Set<String> keys = redisTemplate.keys("*");
        for (String key : keys) {
            // 从redis获取信息
            Set<String> members = redisTemplate.opsForSet().members(key);
            // 删除redis记录
            Boolean delete = redisTemplate.delete(key);
            String status = "";
            for (String member : members) {
                status = member;
            }
            // 更新数据库信息
            updateTopicLikesRelation(key, status);
        }
    }

    @Autowired
    private UserLikesRecordService userLikesRecordService;

    /**
     * 更新数据库信息
     */
    private void updateTopicLikesRelation(String key, String status) {
        String[] ids = key.split(":");
        if (ids.length < 3) {
//            throw new RRException("key错误");
            return ;
        }
        String topicType = ids[0], topicId = ids[1], userId = ids[2];
        // 1.检查是否已经存在记录
        UserLikesRecordEntity entity = userLikesRecordService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<UserLikesRecordEntity>()
                        .eq(UserLikesRecordEntity::getUserId, Long.valueOf(userId))
                        .eq(UserLikesRecordEntity::getTopicId, Long.valueOf(topicId))
                        .eq(UserLikesRecordEntity::getTopicType, topicType));
        // 2.更新或者插入
        if (ObjectUtils.isEmpty(entity)) {
            // 插入
            UserLikesRecordEntity record = new UserLikesRecordEntity();
            record.setUserId(Long.valueOf(userId));
            record.setTopicId(Long.valueOf(topicId));
            record.setTopicType(topicType);
            userLikesRecordService.save(record);
        }
        //因为如果存在记录则代表点赞，那么如果当前状态未0则删除数据库记录
        else if ("0".equals(status)) {
            userLikesRecordService.removeById(entity.getId());
        }

    }
}
